package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.system.domain.ComingOut;
import com.ruoyi.system.domain.TbComingOutLog;
import com.ruoyi.system.domain.vo.ComingOutRequest;
import com.ruoyi.system.domain.vo.ComingOutVO;
import com.ruoyi.system.domain.vo.OperationType;
import com.ruoyi.system.mapper.ComingOutLogMapper;
import com.ruoyi.system.mapper.ComingOutMapper;
import com.ruoyi.system.service.ComingOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ComingOutServiceImpl implements ComingOutService {

    @Autowired
    private ComingOutMapper comingOutMapper;

    @Autowired
    private ComingOutLogMapper logMapper;

    @Override
    public void handleOperation(ComingOutRequest request) {
        // 1. 查询或初始化库存记录
        ComingOut record = comingOutMapper.selectByCategoryId(request.getCategoryId());
        if (record == null) {
            record = new ComingOut();
            record.setCategoryId(request.getCategoryId());
            comingOutMapper.insert(record);
        }

        // 2. 计算新值
        int before = record.getSurplusCount();
        int after = before;
        if (request.getOperationType() == OperationType.OUTBOUND) { // 出库
            after = before - request.getOperationNum();
            record.setOutCount(record.getOutCount() + request.getOperationNum());
        } else { // 进库
            after = before + request.getOperationNum();
            record.setComingCount(record.getComingCount() + request.getOperationNum());
        }
        record.setSurplusCount(after);

        // 3. 更新库存
        comingOutMapper.updateById(record);

        // 4. 记录日志
        TbComingOutLog log = new TbComingOutLog();
        log.setCategoryId(request.getCategoryId());
        log.setOperationType(request.getOperationType().getCode());
        log.setOperationBeforeCount(before);
        log.setOperationNum(request.getOperationNum());
        log.setOperationAfterCount(after);
        logMapper.insert(log);
    }
    @Override
    public List<ComingOutVO> getStockList() {
        // 1. 查询有效库存记录
        List<ComingOut> entities = comingOutMapper.selectList(
                new QueryWrapper<ComingOut>()
                        .eq("del_flag", "0")
        );

        // 2. 转换为VO对象
        return entities.stream()
                .map(ComingOutVO::fromEntity)
                .collect(Collectors.toList());
    }
}